package controller

import "api/app/{{ table.path }}/auto/v1/api"
{% if model == "tree" %}
import "api/app/{{ table.path }}/models"
import "gitee.com/dreamwood/ez"
import "gitee.com/dreamwood/ez/server"
{% endif %}

type {{ table.name }}Controller struct {
api.{{ table.name }}Api
}

func init() {

c := &{{ table.name }}Controller{}
c.Prepare()
c.AddRoute("/list", c.ListAction)
c.AddRoute("/get", c.GetAction)
c.AddRoute("/scan", c.ScanAction)
c.AddRoute("/choice", c.ChoiceAction)
c.AddRoute("/save", c.SaveAction)
c.AddRoute(`/save_many`, c.SaveManyAction)
c.AddRoute("/delete", c.DeleteAction)
c.AddRoute("/delete_many", c.DeleteManyAction)
c.AddRoute("/copy", c.CopyAction)
{% if model == "tree" %}
c.AddRoute(`/tree`, c.Tree)
{% endif %}
}

//如果不满意自动生成的方法，请自定义，本文件不会被生成器覆盖，请放心操作
//func (this *{{ table.name }}Controller) SaveAction(operation *server.Operation) {}
//func (this *{{ table.name }}Controller) GetAction(operation *server.Operation) {}
//func (this *{{ table.name }}Controller) ScanAction(operation *server.Operation) {}
//func (this *{{ table.name }}Controller) ListAction(operation *server.Operation) {}
//func (this *{{ table.name }}Controller) DeleteAction(operation *server.Operation) {}



{% if model == "tree" %}
func (c *{{ table.name }}Controller) Tree(operation *server.Operation) {
root := operation.Get("root").IsInt(0)
op := c.TakeOver(operation)
crud := models.New{{ table.name }}Crud()
condition := ez.M{}
if root != 0 {
rootModel, e := crud.Find(root)
if op.CheckError(e) {
return
}
condition = ez.M{"l__gt": rootModel.L, "r__lt": rootModel.R}
}
full, e := crud.FindBy(condition, []string{"l"}, 0, 0)
if op.CheckError(e) {
return
}
data := c.createTree(root, full)
op.ReturnSuccess("OK", data)
}

func (c *{{ table.name }}Controller) createTree(root int, full []*models.{{ table.name }}) []map[string]interface{} {
//获取第一层Root
finds := make([]*models.{{ table.name }}, 0)
for _, md := range full {
if md.ParentId == root {
finds = append(finds, md)
}
}
re := make([]map[string]interface{}, 0)
for _, find := range finds {
cur := make(map[string]interface{})
//分类树所需数据结构
cur["id"] = find.Id
cur["title"] = find.Name
//级联选择器所需数据结构
cur["value"] = find.Id
cur["label"] = find.Name
cur["children"] = c.createTree(find.Id, full)
re = append(re, cur)
}
return re
}


func (c *{{ table.name }}Controller) UpdateLeftRight(operation *server.Operation) {
models.{{ table.name }}TreeModel{}.UpdateLeftAndRight(0, 0, 0)
}
{% endif %}